<?php

namespace App\Http\Controllers\Myorders;

use App\Common\Result;
use App\Http\Controllers\Controller;
use App\Models\Customer\CustomerModel;
use App\Models\Goods\GoodsModel;
use App\Models\Inquiry\InquirySheet;
use App\Models\Quote\Quotation;
use App\Service\Balance\BalanceService;
use App\Service\Cart\CartService;
use App\Service\Customer\AddressService;
use App\Service\Customer\CustomerService;
use App\Service\Easemob\EasemobService;
use App\Service\Goods\GoodsService;
use App\Service\Indent\OrderService;
use App\Service\Inquiry\InquiryService;
use App\Service\Jpush\JpushService;
use App\Service\ServiceLog;
use App\Service\Work\BestWorksService;
use Illuminate\Http\Request;
use DB;

class OrderController extends Controller
{
    /**
     * 生成单个订单
     * @param Request $request
     */
    public function createOrder(Request $request)
    {
        Result::isEmpty($uid = $request->uid,'无有效用户信息',-16);
        Result::isEmpty($inquiry_sheet_id = $request->inquiry_sheet_id,'无有效信息',-31);
        $address_id = $request->address_id;
        $remark = $request->remark;

        if(!CustomerService::findUser(['uid' => $request->uid])){
            Result::msg('-16','error','无有效用户信息');
        }

        //获得询价单
        $inquiry_sheet_info = InquiryService::oneInquirySheet($uid,$inquiry_sheet_id);
        if(!$inquiry_sheet_info){
            Result::msg(-1,'error','未找到询价单');
        }
        if($inquiry_sheet_info['status'] != 1){
            Result::msg(-1,'error','询价单状态有误');
        }

        if(!$address = AddressService::getOneAddress($address_id,$uid)){
	        Result::msg('-56','error','无有效地址');
        }

        $order_id = OrderService::generateOrderId($request->uid);

        DB::beginTransaction();
        try{
            $data = array(
                'order_id' => $order_id,
                'inquiry_sheet_id' => $inquiry_sheet_info->id,
                'uid' => $uid,
                'price' => $inquiry_sheet_info->quote_price
            );
            if($remark){
                $data['remark'] = $remark;
            }

            if(!OrderService::addOrderAddress($address,$order_id,$uid)){
                DB::rollBack();
                Result::msg('-22','error','订单失败');
            }

            if(!$order = OrderService::createOrder($data)){
                DB::rollBack();
                Result::msg('-22','error','订单失败');
            }

            //修改询价单状态
            $inquiry_sheet_info->status = 3;
            $inquiry_sheet_info->save();

            //修改报价单状态
            $quotations = Quotation::where('inquiry_sheet_id',$inquiry_sheet_info->id)->first();
            $quotations->status = 3;
            $quotations->save();

            DB::commit();
        }catch (\Exception $e){

            DB::rollBack();
            Result::msg('-22','error','订单失败');
        }

        Result::msg('0','success',[
            'order' => $order,
            'inquiry' =>  $inquiry_sheet_info
        ]);
    }

    /**
     * 订单确认页面
     */
    public function confirmOrder(Request $request)
    {
        Result::isEmpty($uid = $request->uid,'无有效用户信息',-16);
        Result::isEmpty($goods_id = $request->goods_id,'无有效信息',-31);
        Result::isEmpty($number = $request->number,'无有效信息',-31);

        if(!CustomerService::findUser(['uid' => $request->uid])){
            Result::msg('-16','error','无有效用户信息');
        }

        $goods_info = GoodsService::getGoodsIdInfo($goods_id);

        if(!$goods_info || $goods_info['is_up'] === 0){
            Result::msg('-44','error','商品已经下架');
        }

        if($goods_info['stock'] <$number){
            Result::msg('-','error','库存不足');
        }

        $address = AddressService::defaultAddress($uid);

        $goods = [
            'goods_id' => $goods_id,
            'name' => $goods_info['name'],
            'orgin_price' => $goods_info['orgin_price'],
            'current_price' => $goods_info['current_price'],
            'thumb' => $goods_info['thumb'],
            'stock' => $goods_info['stock'],
            'spec' => $goods_info['spec'],
            'description' => $goods_info['description']
        ];

        $result = [
            'address' => $address,
            'goods'=> $goods,
            'price' => $goods_info['current_price']*$number,
            'number' => $number
        ];

        Result::msg('0','success',$result);
    }


    /**
     * 购物车订单确认页面
     */
    public static function cartConfirmOrder(Request $request)
    {
        Result::isEmpty($uid = $request->uid,'无有效用户信息',-16);
        Result::isEmpty($cart_ids = $request->cart_ids,'无有效信息',-31);

        if (!isset($cart_ids) || !is_array($cart_ids = explode(',', $request->cart_ids))) {
            Result::msg('-22','error','无效购物车');
        }

        $goods_info = CartService::getGoodsInCart($cart_ids,$uid);

        if(count($cart_ids) !== count($goods_info)) {
            Result::msg('-44','error','商品已经下架');
        }

        $address = AddressService::defaultAddress($uid);

        $result = [
            'address' => $address,
            'goods'=> $goods_info
        ];

        Result::msg('0','success',$result);
    }

    /**
     * 生成购物车订单
     */
    public function createCartOrder(Request $request)
    {
        $cart_ids = $request->cart_ids;
        $uid = $request->uid;
        $address_id = $request->address_id;

        if (!isset($cart_ids) || !is_array($cart_ids = explode(',', $cart_ids))) {
            Result::msg('-22','error','无效购物车');
        }

        $goods_info = CartService::getGoodsInCart($cart_ids,$uid);

        if(count($cart_ids) !== count($goods_info)) {
            Result::msg('-44','error','商品已经下架');
        }

	    if(!$address = AddressService::getOneAddress($address_id,$uid)){
		    Result::msg('-56','error','无有效地址');
	    }

        $order_id = OrderService::generateOrderId($request->uid);

        DB::beginTransaction();

        try{
            $price_array = array_column($goods_info,'price');
            $price = array_sum($price_array);

            $data = array(
                'order_id' => $order_id,
                'price' => $price,
                'uid' => $uid,
            );
            //插入订单地址
	        if(!OrderService::addOrderAddress($address,$order_id,$uid)){
		        DB::rollBack();
		        Result::msg('-22','error','订单失败');
	        }

            //插入订单
            if(!OrderService::createOrder($data)){
                DB::rollBack();
                Result::msg('-23','error','订单失败');
            }


            //插入订单商品
            $goods = array_map(function ($goods) use($order_id){
                return [
                    'order_id' => $order_id,
                    'goods_id' => $goods['goods_id'],
                    'name' => $goods['name'],
                    'orgin_price' => $goods['orgin_price'],
                    'current_price' => $goods['current_price'],
                    'thumb' => $goods['thumb'],
                    'stock' => $goods['stock'],
                    'spec' => $goods['spec'],
                    'description' => $goods['description'],
                    'number' => $goods['number']
                ];
            },$goods_info);

            if(!OrderService::createCartOrderGoods($goods)){
                DB::rollBack();
                Result::msg('-24','error','订单失败');
            }


            //减少库存
            foreach ($goods_info as $good){
                if(!GoodsService::reduceStock($good['goods_id'],$good['number'])){
                    DB::rollBack();
                    Result::msg('-22','error','订单失败');
                }
            }
            //删除购物车
            if(!CartService::delCarts($cart_ids,$uid)){
                DB::rollBack();
                Result::msg('-22','error','订单失败');
            }

            DB::commit();
            Result::msg('0','success',$data);
        }catch (\Exception $e){
            DB::rollBack();
            Result::msg('-22','error','订单失败');
        }
    }

    /**
     * 充值生成订单
     * @param Request $request
     */
    public function chargeCreateOrder(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息',-16);
        $price = $request->price;
        if($price<1){
            Result::msg('-33','error','充值金额不能少于1元');
        }
        if(!CustomerService::findUser(['uid' => $request->uid])){
            Result::msg('-16','error','无有效用户信息');
        }

        $order_id = OrderService::generateOrderId($request->uid);
        $data = array(
            'order_id' => $order_id,
            'price' =>$price,
            'uid' => $request->uid,
            'auid' => '',
            'article_id' => 0,
            'order_type' => 3, //充值状态
            'ship_address' => ''
        );

        if(!OrderService::createOrder($data)){
            Result::msg('-22','error','订单失败');
        }

        Result::msg('0','success',$data);
    }

	public function myBuys(Request $request)
    {
        $uid = $request->uid;
        $page = $request->page;
        $offest = ($page-1)*10;
        if(!CustomerService::findUser(['uid' => $uid])){
            Result::msg('-16','error','无有效用户信息');
        }
        $buys = OrderService::getMyBuys($uid,10,$offest);
        if($buys){
            Result::msg('0',"success",$buys);
        }else{
            Result::msg('-18',"error","没有更多了");
        }
    }
	
	 /**
     * 我的收入总额
     */
    public function mySumIncome(Request $request)
    {
        $uid = $request->uid;
        if(!CustomerService::findUser(['uid' => $uid])){
            Result::msg('-16','error','无有效用户信息');
        }
        $incomes = OrderService::getMyIncome($uid);
		$result = array(
			'incomes' => $incomes
		);
        Result::msg('0',"success",$result);
    }

    /**
     * 买家确认收货
     */
    public function receiveGoods(Request $request)
    {
        $order_id = $request->orderid;
        if(!$order_info = OrderService::getOrder($order_id)){
            Result::msg('-23','error','无效订单');
        }

        //控制订单
        if($order_info['price']<=0 || $order_info['status'] != 2){
            Result::msg('-23','error','无效订单');
        }

        DB::beginTransaction();
        try{
            $order_data = array(
                'status' => 3,
				'updated_at' => date("Y-m-d H:i:s")
            );
            $detail_data = array(
                'order_id' => $order_info->order_id,
                'remark' => '买家确认收货', //确认收货
				'status' => 3,
                'created_at' => date("Y-m-d H:i:s")
            );

            //增加销量
            $inquiry = InquirySheet::where('id',$order_info->inquiry_sheet_id)->first();
            GoodsModel::where('id',$inquiry->goods_id)->increment('sale_num');

            OrderService::changeOrder($order_info->order_id,$order_data);
            OrderService::addOrderDetail($detail_data);

            CustomerModel::where('uid',$inquiry->quote_uid)->increment('order_num');
            CustomerModel::where('uid',$inquiry->quote_uid)->increment('commission',$order_info->price);

			DB::commit();
        }catch (\Exception $e){
            DB::rollback();
            ServiceLog::record("error.txt",$e->getMessage(),"error");
            Result::msg('-32','error','订单失败');
        }


        Result::msg('0','success',[]);
    }

    /**
     * 订单查询
     */
    public function queryOrder(Request $request)
    {
        $uid = $request->uid;
        $order_status = isset($request->status)?$request->status:0;

        $result = OrderService::selectMyOrder($order_status,$uid);

        if(!$result->items()){
            Result::msg('700','success',[]);
        }

        Result::msg('0','success',$result);
    }
	
	/**
     * 订单详情
     */
    public function orderDetail(Request $request)
    {
        $uid = $request->uid;
        $order_id = $request->oid;

        $result = OrderService::getOrderDetail($order_id,$uid);
		
        if(!$result){
            Result::msg('-36','error','订单不存在');
        }
	
        switch ($result->status){
            case 0:
                $result->statusStr = '未付款';
                break;
            case 1:
                $result->statusStr = '已付款';
                break;
            case 2:
                $result->statusStr = '已发货';
                break;
            case 3:
                $result->statusStr = '已确认收货';
                break;
            case 4:
                $result->statusStr = '已完成';
        }

        Result::msg('0','success',$result);
    }
}
        